package javabasics.netty.demo3;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

/**
 * @Author suxiaoxiao
 * @Date 2019/9/16 21:40
 * @Version 1.0
 */
public class ByteBufTest {

    public static void main(String[] args) {
        // 创建一个 初始容量为 9，最大容量为 100 的 ByteBuf
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(9, 100);

        print("allocate ByteBuf(9, 100)", byteBuf);

        // write 方法改变写指针，写完之后指针未到 capacity 的时候，buffer 仍然可写。
        byteBuf.writeBytes(new byte[]{1, 2, 3, 4});
        print("writeBytes(1, 2, 3, 4)", byteBuf);

        // write 方法改变写指针，写完之后写指针未到 capacity 的时候，buffer 仍然可写，写完 int 类型之后，写指针 + 4
        byteBuf.writeInt(12);
        print("writeInt(12)", byteBuf);

        // write 方法改变写指针，写完之后写指针等于 capacity 的时候，buffer 不可写
        byteBuf.writeBytes(new byte[]{5});
        print("writeBytes(5)", byteBuf);

        // write 方法改变写指针，写的时候发现 buffer 不可写则开始扩容，扩容之后 capacity 随机改变
        byteBuf.writeBytes(new byte[]{6});
        print("writeBytes(6)", byteBuf);

        // get 方法不改变读写指针
        System.out.println("getByte(3) return: " + byteBuf.getByte(3));
        System.out.println("getByte(4) return: " + byteBuf.getByte(4));
        System.out.println("getShort(3) return: " + byteBuf.getShort(3));
        System.out.println("getInt(3) return: " + byteBuf.getInt(3));
        print("getByte()", byteBuf);

        // set 方法不改变读写指针
        byteBuf.setByte(byteBuf.readableBytes() + 1, 0);
        print("setByte()", byteBuf);

        // read 方法改变读指针
        byte[] dst = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(dst);
        print("readBytes(" + dst.length + ")", byteBuf);

    }

    private static void print(String action, ByteBuf byteBuf) {
        System.out.println("==============" + action + "===============");
        // 当前容量
        System.out.println("capacity(): " + byteBuf.capacity());
        // 最大容量
        System.out.println("maxCapacity(): " + byteBuf.maxCapacity());
        // 读指针位置
        System.out.println("readerIndex(): "+ byteBuf.readerIndex());
        // 可读的字节数量
        System.out.println("readableBytes(): " + byteBuf.readableBytes());
        // 是否可读
        System.out.println("isReadable(): " + byteBuf.isReadable());
        // 读指针位置
        System.out.println("writerIndex(): " + byteBuf.writerIndex());
        // 可写的字节数量
        System.out.println("writableBytes(): " + byteBuf.writableBytes());
        // 是否可写
        System.out.println("isWritable(): " + byteBuf.isWritable());
        // 还可以写入多少字节
        System.out.println("maxWritableBytes(): " + byteBuf.maxWritableBytes());
        System.out.println();
    }

}
